package reference

import (
	"encoding/json"
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi "github.com/alibabacloud-go/dysmsapi-20170525/v3/client"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/leonscriptcc/bondman/configs"
	"log"
)

type SMS struct {
	client *dysmsapi.Client
	msgs   chan string
}

// NewSMS 初始化阿里短信服务
func NewSMS(msgs chan string) (*SMS, error) {
	// 配置阿里短信服务链接
	config := &openapi.Config{
		// 您的AccessKey ID
		AccessKeyId: &configs.Parameters.AliSms.AccessKeyId,
		// 您的AccessKey Secret
		AccessKeySecret: &configs.Parameters.AliSms.AccessKeySecret,
	}
	// 访问的域名
	config.Endpoint = tea.String(configs.Parameters.AliSms.Endpoint)

	// 实例化一个客户端
	client, err := dysmsapi.NewClient(config)
	if err != nil {
		return nil, err
	}

	return &SMS{client: client, msgs: msgs}, nil
}
func (s *SMS) Start() {
	for {
		select {
		case msg := <-s.msgs:
			s.sendBatchSms(msg)
		}
	}
}

// sendBatchSms 批量发送短信
func (s *SMS) sendBatchSms(msg string) {
	request := &dysmsapi.SendBatchSmsRequest{}
	// 设置群发手机号
	b, _ := json.Marshal(configs.Parameters.AliSms.PhoneNumbers)
	request.SetPhoneNumberJson(string(b))
	// 设置签名
	b, _ = json.Marshal(configs.Parameters.AliSms.SignNames)
	request.SetSignNameJson(string(b))
	// 设置模板code
	request.SetTemplateCode(configs.Parameters.AliSms.TemplateCode)
	// 设置自定义变量
	var templates []alertTemplate
	for i := 0; i < len(configs.Parameters.AliSms.PhoneNumbers); i++ {
		templates = append(templates, newAlertTemplate(msg))
	}
	b, _ = json.Marshal(templates)
	request.SetTemplateParamJson(string(b))

	response, err := s.client.SendBatchSms(request)
	log.Println(response)
	if err != nil {
		log.Println(err)
	}
}

// QuerySendDetails 查询短信发送详情
func (s *SMS) QuerySendDetails(phone, date string) {
	req := &dysmsapi.QuerySendDetailsRequest{}
	pageSize := int64(10)
	CurrentPage := int64(1)
	req.PhoneNumber = &phone
	req.SendDate = &date
	req.PageSize = &pageSize
	req.CurrentPage = &CurrentPage
	res, err := s.client.QuerySendDetails(req)
	if err != nil {
		log.Println(err)
	}
	log.Println(res)
}

// alertTemplate 告警信息模板
type alertTemplate struct {
	Project string `json:"project"`

	Content string `json:"content"`
}

// newAlertTemplate 新建消息模板
func newAlertTemplate(content string) alertTemplate {
	return alertTemplate{
		Project: fmt.Sprintf("《%s-%s》",
			configs.Parameters.Project,
			configs.Parameters.Mode,
		),
		Content: content,
	}

}
